package com.jinwei.qunguanjia.config;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class WeChatMPConfig {

	@Value("${weChat.mpAppId}")
    private String mpAppId;
	@Value("${weChat.mpAppSecret}")
    private String mpAppSecret;

	@Bean(name="wxMpService")
	public WxMpService wxMaService() {
		WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
		config.setAppId(mpAppId);
		config.setSecret(mpAppSecret);
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);
		return wxMpService;
	}

	public static void main(String[] args) throws WxErrorException {
		WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
		config.setAppId("wx45d11db764fb05b6");
		config.setSecret("b6ebaa150a41570d278e62c32ccf0983");
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);
		//数据
		List<WxMpTemplateData> data = Arrays.asList(
				new WxMpTemplateData("thing1", "kyson"),
				new WxMpTemplateData("time2", "2024-05-07 19:20:00")
		);
		//2,推送消息
		WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
				.toUser("o_hhj5396JBrpdzKoHdFwe7P3hAI")//要推送的用户openid
				.data(data) //数据
				.templateId("tB3SORRpzzOMovuscTMZcRBWMDQKReKUl2fQoRgpe04")//模版id
				.build();
		// 跳转小程序相关配置【跳转的小程序必须是公众号关联的小程序！！！】
		//WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
		// 小程序的appId
		//miniProgram.setAppid("wx0697b3c56aee215d");
		// 小程序的pagePath 注意，这里是支持传参的！！！
		//miniProgram.setPagePath("pages/appt/appt");
		// 需要跳转首页时，需要设置 usePath = true (默认是 false，只跳转非首页)
		//miniProgram.setUsePath(true);
		//templateMessage.setMiniProgram(miniProgram);
		//发起推送
		String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
		System.out.println("推送成功：" + msg);
	}

}
